<template>
  <div class="app-container">
    <el-form :inline="true" v-model="listQuery">
      <el-form-item>
        <el-input v-model="listQuery.keyword" placeholder="关键词搜索" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="listQuery.state" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in adminStateMap"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList()">查询</el-button>
        <el-button icon="el-icon-circle-plus-outline" type="primary" @click="openForm('dialogForm', {})">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
    >
      <el-table-column label="序号" type="index"></el-table-column>

      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="账号" prop="phone"></el-table-column>
      <el-table-column label="角色" prop="role_names" min-width="180" show-overflow-tooltip></el-table-column>
      <el-table-column label="是否超管">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.is_super" :active-value="1" :inactive-value="0" disabled></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="0" disabled></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-link @click="openForm('dialogForm', scope.row)" :underline="false" type="primary" style="margin-right: 10px;">编辑</el-link>
          <el-link @click="deleteAdmin(scope.row)" v-loading="scope.row.loading" :underline="false" type="danger">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.page_size" @pagination="getList()" />

    <el-dialog
      :title="formTitleMap[formState]"
      :visible="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dialogForm"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="昵称" required prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="账号" required prop="phone">
          <el-input v-model.trim.number="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" required prop="password">
          <el-input v-model.trim="form.password" type="password" placeholder="请输入登录密码"></el-input>
        </el-form-item>
        <el-form-item label="重复密码" required prop="password_confirm">
          <el-input v-model.trim="form.password_confirm" type="password" placeholder="请再次输入登录密码"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role_ids" multiple placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="item in roleAll"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="form.state" :label="1">启用</el-radio>
          <el-radio v-model="form.state" :label="0">禁用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="formState==='create'" type="primary" :loading="formLoading" @click="createAdmin('dialogForm')">立即新增</el-button>
        <el-button v-else type="primary" :loading="formLoading" @click="updateAdmin('dialogForm')">立即更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createAdmin, updateAdmin, deleteAdmin } from '@/api/system/admin'
import { getRoleAll } from '@/api/system/role'
import {isEmpty, Message, MessageBox} from 'element-ui'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'SettingSystemAdminIndex',
  components: { Pagination },
  data() {
    // 自定义验证规则
    const checkConfirmPassword = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        keyword: '',
        state: null,
        page: 1,
        page_size: 20
      },
      dialogFormVisible: false,
      formState: 'create',
      formLoading: false,
      formTitleMap: {
        create: '新增账号',
        update: '编辑账号'
      },
      form: {
        id: 0,
        name: '',
        phone: '',
        password: '',
        password_confirm: '',
        state: 1,
        role_ids: ''
      },
      ruleForm: {
        name: '',
        phone: '',
        password: '',
        password_confirm: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '长度必须大于等于 6 个字符', trigger: 'blur' }
        ],
        password_confirm: [
          { required: true, message: '请输入重复密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '长度必须大于等于 6 个字符', trigger: 'blur' },
          { validator: checkConfirmPassword, trigger: 'blur' }
        ]
      },
      adminStateMap: [
        {
          value: '-1',
          label: '全部'
        },
        {
          value: '1',
          label: '启用'
        },
        {
          value: '0',
          label: '禁用'
        }
      ],
      roleAll: null
    }
  },
  created() {
    this.getList()
    this.getRoleAll()
  },
  methods: {
    getRoleAll() {
      getRoleAll().then((res) => {
        this.roleAll = res.data
      }).catch((res) => {})
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(res => {
        this.list = res.data.list
        this.total = res.data.pager.total
        this.listQuery.page = res.data.pager.page
        this.listQuery.page_size = res.data.pager.page_size
      }).catch((res) => {})
      this.listLoading = false
    },
    resetFormData() {
      this.form = {
        id: 0,
        name: '',
        phone: '',
        password: '',
        password_confirm: '',
        state: 1,
        role_ids: ''
      }
    },
    openForm(formName, row = {}) {
      this.dialogFormVisible = true
      if (row.id) {
        // 设置表单
        this.formState = 'update'
        if (row.role_ids && row.role_ids.length) {
          row.role_ids = row.role_ids.split(',').map((item) => {
            return parseInt(item)
          })
        }
        this.form = row
      } else {
        this.formState = 'create'
      }
      if (this.formState === 'create') {
        this.resetFormData()
      }
      this.$nextTick(() => {
        this.$refs['dialogForm'].clearValidate()
      })
    },
    createAdmin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formLoading = true
          createAdmin(this.form).then(res => {
            this.getList()
            this.dialogFormVisible = false
            Message.success(res.msg)
          }).catch(res => {})
          this.formLoading = false
        } else {
          return false
        }
      })
    },
    updateAdmin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.formLoading = true
          updateAdmin(this.form).then(res => {
            this.getList()
            this.dialogFormVisible = false
            Message.success(res.msg)
          }).catch(res => {})
          this.formLoading = false
        } else {
          return false
        }
      })
    },
    deleteAdmin(row) {
      row.loading = true
      MessageBox.confirm(`请确认是否删除【${row.name}】账号？删除后无法恢复！`, '温馨提示', {
        type: 'warning'
      }).then(() => {
        deleteAdmin({ id: row.id }).then(res => {
          this.getList()
          this.dialogFormVisible = false
          Message.success(res.msg)
        }).catch(res => {})
      }).catch(() => {
        Message.info('已取消')
      })
      row.loading = false
    }
  }
}
</script>

<style scoped>

</style>
